<script setup>
import { ref, reactive, watch, computed, onMounted } from 'vue'
import { useUserStore } from '@/stores/user.store.js'
import { useRoute, useRouter } from 'vue-router'
import api from "@/api/api";
import keyboard from "@/components/number-plate/keybord.vue";
import { formatTime } from "@/utils/common";

// 组件注册
const VnpKeyboard = keyboard;

// 实例相关
const store = useUserStore();
const route = useRoute();
const router = useRouter();

// 响应式数据
const val = ref("");
const keyboardList = ref(["浙", "", "", "", "", "", "", ""]);
const show = ref(false);
const index = ref(-1);
const type = ref("cn");
const isNewEnergy = ref(false);
const checked = ref(false);
const showTime = ref(false);
const dateValue = ref('')

const field = reactive({
  ownerName: "",
  ownerPhone: "",
  brand: "",
  mileage: "",
  purchasingDate: "",
});

const carInfo = ref({});
const pageType = ref("add");

// Computed
const userData = computed(() => store.userData);
const carList = computed(() => store.carList);

// Watch
watch(val, (newVal) => {
  keyboardList.value[index.value] = newVal;
  if (index.value < keyboardList.value.length - 1) {
    index.value++;
    type.value = "en";
  } else {
    index.value = -1;
    show.value = false;
  }
});

watch(show, (newVal) => {
  if (!newVal) {
    index.value = -1;
  }
});

// 方法
const onClickLeft = () => {
  router.back();
};

const handleClickKey = (i) => {
  if (i == 0) {
    index.value = i;
    show.value = true;
    type.value = "cn";
    return;
  } else {
    if (keyboardList.value[i - 1] == "") {
      return;
    } else {
      index.value = i;
      type.value = "en";
      show.value = true;
    }
  }
};

const del = () => {
  if (index.value > 0) {
    if (keyboardList.value[index.value]) {
      keyboardList.value.splice(index.value, 1, "");
    } else {
      index.value--;
      if (index.value == 0) {
        type.value = "cn";
      }
      keyboardList.value.splice(index.value, 1, "");
    }
  } else if (index.value == 0) {
    keyboardList.value.splice(index.value, 1, "");
  }
};

const selectTime = (val) => {
  field.purchasingDate = formatTime(val);
  showTime.value = false;
};

const onSubmit = () => {
  if (pageType.value == "add") {
    addCar();
  } else {
    editCar();
  }
};

const addCar = async () => {
  let plate = keyboardList.value.join("");
  if (plate.trim().length < 7) {
    showToast("请输入完整车牌号");
    return;
  }
  if (!field.brand) {
    showToast("请输入车辆品牌");
    return;
  }
  let params = {
    ...field,
    plateNumber: plate,
  };
  await api.addCar(params);
  let res = await api.getCarList({});
  store.setCarList(res.data);
  showToast({
    message: "添加成功",
    duration: 1200,
  });
  setTimeout(() => {
    router.back();
  }, 1200);
};

const editCar = async () => {
  let plate = keyboardList.value.join("");
  if (plate.trim().length < 7) {
    showToast("请输入完整车牌号");
    return;
  }
  if (!field.brand) {
    showToast("请输入车辆品牌");
    return;
  }
  let params = {
    ...field,
    plateNumber: plate,
  };

  await api.updateCarInfo(params);
  let res = await api.getCarList({});
  store.setCarList(res.data);
  showToast({
    message: "编辑成功",
    duration: 1200,
  });
  setTimeout(() => {
    router.back();
  }, 1200);
};

// 生命周期
onMounted(() => {
  field.ownerName = userData.value.userName;
  field.ownerPhone = userData.value.phone;
  let id = route.query.id ?? null;
  pageType.value = route.query.type ?? pageType.value;
  if (pageType.value == "edit") {
    carInfo.value = carList.value.find((v) => v.id == id);
    field.brand = carInfo.value.brand;
    field.mileage = carInfo.value.mileage;
    field.id = id;
    field.purchasingDate = carInfo.value.purchasingDate;
    keyboardList.value = carInfo.value.plateNumber
      .split("")
      .map((item) => item.trim());
    if (keyboardList.value.length == 7) {
      keyboardList.value.push("");
    }
  }
});
</script>
<template>
  <div class="addCar">
    <van-nav-bar title="添加爱车" fixed safe-area-inset-top @click-left="onClickLeft" />
    <div class="box">
      <div class="title">输入车牌</div>
      <div class="number">
        <div v-for="(v, i) in keyboardList" :key="i" class="number_item" :class="{
          active: index == i,
          green: i == keyboardList.length - 1 && !v && index != i,
        }" @click="handleClickKey(i)">
          {{ v }}
        </div>
      </div>
    </div>
    <div class="check-box">
      <van-checkbox v-model="checked">已阅读并同意《用户信息授权说明》
      </van-checkbox>
    </div>
    <div class="form">
      <van-form @submit="onSubmit">
        <van-field v-model="field.ownerName" label="车主姓名" placeholder="请输入" />
        <van-field v-model="field.ownerPhone" label="车主手机号" type="digit" placeholder="请输入" />
        <van-field v-model="field.brand" label="车辆品牌" placeholder="请输入" />
        <van-field v-model="field.mileage" label="行驶里程数" type="digit" placeholder="请输入" />
        <van-field v-model="field.purchasingDate" label="购买时间" placeholder="请选择" readonly clickable
          @click="showTime = true" />
        <van-popup v-model:show="showTime" position="bottom">
          <van-date-picker :model-value="dateValue" @confirm="selectTime" @cancel="showTime = false" />
        </van-popup>
        <div class="submit">
          <van-button round block type="primary" native-type="submit">保存
          </van-button>
        </div>
      </van-form>
    </div>
    <vnp-keyboard v-model="val" :show="show" :keybordType="type" @del="del"></vnp-keyboard>
  </div>
</template>


<style lang="less" scoped>
.addCar {
  min-height: 100vh;
  background: url("https://zxcxappimg.oss-cn-hangzhou.aliyuncs.com//zxcxmall/2025/05/29/44dea588672142d48f873df92c7b625e.jpg") no-repeat;
  background-size: cover;
  background-attachment: local;
  background-position: top center;
  box-sizing: border-box;
  padding: 150px 60px 60px 60px;
  position: relative;

  .box {
    width: 100%;
    padding: 55px 30px 35px 30px;
    background: #fff;
    margin-top: 80px;
    border-radius: 15px;

    .title {
      font-size: 44px;
      color: #000;
      margin-bottom: 50px;
      letter-spacing: 4px;
    }

    .number {
      display: flex;
      justify-content: space-between;
      align-items: center;

      &_item {
        width: calc(100% / 8 - 10px);
        height: 160px;
        background: #f5f5f5;
        border-radius: 10px;
        color: #000;
        font-weight: bold;
        text-align: center;
        line-height: 160px;
        font-size: 39px;
      }

      .green {
        background: #d9feec;
        border: 3px dashed #7fd5b2;
        color: #56d3a1;
      }

      .number_item_D {
        font-size: 35px;
        padding: 0 5px;
      }

      .active {
        background: #fee9f0;
      }
    }
  }

  .check-box {
    margin: 50px 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 30px;
    font-size: 30px;

    :deep(.van-checkbox) {
      display: flex;
      align-items: center;
      overflow: initial;
    }

    :deep(.van-checkbox__icon) {
      display: flex;
      align-items: center;
    }

    :deep(.van-checkbox__icon--round) {
      font-size: 38px;
    }

    :deep(.van-checkbox__label) {
      margin-left: 25px;
    }
  }

  .form {

    :deep(.van-cell) {
      display: flex;
      align-items: center;
      font-size: 44px;
      background: transparent;
      padding: 30px 20px;

      .van-field__label {
        color: #000 !important;
        margin-right: 20px;
      }

      .van-field__control {
        background-color: #fff;
        border-radius: 20px;
        box-sizing: border-box;
        padding: 25px 20px;
        border: 3px solid #b5c0cc;
        font-size: 30px;
      }


      input::placeholder {
        color: #000;
        font-size: 30px;
      }
    }

    .submit {
      display: flex;
      justify-content: center;
      margin-top: 150px;
      width: 100%;
      padding: 0 100px;

      :deep(.van-button) {
        width: 80%;

      }
    }
  }

  :deep(.van-nav-bar__left) {
    .van-icon {
      color: #303030;
      font-weight: bold;
    }
  }

  :deep(.van-overlay) {
    background: transparent !important;
  }
}

:deep(.van-nav-bar__content) {
  height: 100px;
  margin: 25px auto;
}

:deep(.van-nav-bar__title) {
  font-size: 54px;
  font-weight: 500;
}

:deep(.van-ellipsis) {
  overflow: initial;
}

:deep(.van-button--normal) {
  padding: 60px 0 !important;
}

:deep(.van-button__text) {
  font-size: 44px;
}
</style>
